class Solution
{
public:
    int eatenApples(vector<int>& apples, vector<int>& days)
    {
        int n = apples.size(), ans = 0;
        // 最小堆，存放最早腐烂的苹果
        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;

        // for(int i = 0; i < n || !pq.empty(); i++)
        int i = 0;
        for(i = 0; i < n; i++)
        {
            while(!pq.empty() && pq.top().first == i)
            {
                // 已腐烂
                pq.pop();
            }

            if(i < n && apples[i] > 0)
            {
                pq.emplace(i + days[i], apples[i]);
            }

            // 模拟一天吃一个
            if(!pq.empty())
            {
                ans++;
                auto [rottenDay, num] = pq.top();
                pq.pop();
                if(num > 1)
                    pq.emplace(rottenDay, num - 1);
            }
        }

        // 优化
        while (true)
        {
            while (!pq.empty() && pq.top().first <= i)
            { 
                // 已腐烂
                pq.pop();
            }
            if (pq.empty())
                return ans;
            
            auto [rotten_day, num] = pq.top();
            pq.pop();
            int k = min(num, rotten_day - i);
            ans += k;
            i += k;
        }

        return ans;
    }
};